﻿using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using RimWorld.Planet;
using Verse;

namespace RimZombieGirl
{
    public class TileMutatorWorker_MassGraveyard : TileMutatorWorker
    {
        public TileMutatorWorker_MassGraveyard(TileMutatorDef def) : base(def) { }

        public override void GeneratePostTerrain(Map map)
        {
            base.GeneratePostTerrain(map);

            IntVec3 center = map.Center;

            // 1. 清理中心区域（半径 50）
            foreach (IntVec3 cell in GenRadial.RadialCellsAround(center, 50f, true))
            {
                if (!cell.InBounds(map)) continue;
                map.terrainGrid.SetTerrain(cell, TerrainDefOf.Gravel);
                map.roofGrid.SetRoof(cell, null);

                Plant plant = cell.GetPlant(map);
                if (plant != null) plant.Destroy(DestroyMode.Vanish);
            }

            // 2. 放置一些碎石
            for (int i = 0; i < 50; i++)
            {
                IntVec3 c = CellFinder.RandomClosewalkCellNear(center, map, 50);
                if (!c.InBounds(map)) continue;
                Thing rubble = ThingMaker.MakeThing(ThingDefOf.Filth_RubbleBuilding);
                GenPlace.TryPlaceThing(rubble, c, map, ThingPlaceMode.Direct);
            }

            // 3. 外围布置枯树：90% RI_Building_DeathTree, 10% Plant_TreeHarbinger
            for (int i = 0; i < 120; i++)
            {
                IntVec3 c = CellFinder.RandomClosewalkCellNear(center, map, 50);
                if (!c.InBounds(map) || !c.Standable(map)) continue;

                ThingDef treeDef;
                if (ModsConfig.AnomalyActive)
                {
                    treeDef = (Rand.Value < 0.1f) ? ThingDefOf.Plant_TreeHarbinger : ThingDef.Named("RI_Building_DeathTree");
                }
                else
                {
                    treeDef = ThingDef.Named("RI_Building_DeathTree");
                }

                Thing tree = ThingMaker.MakeThing(treeDef);
                GenSpawn.Spawn(tree, c, map, WipeMode.Vanish);
            }

            // 4. 中心生成 49 个不重叠、随机旋转的 1x2 诅咒坟墓
            ThingDef cursedGraveDef = ThingDef.Named("RI_CursedGrave"); 
            int targetCount = 49;
            int placed = 0;
            int attempts = 0;
            int maxAttempts = 1000; // 尝试上限，防止无限循环

            while (placed < targetCount && attempts < maxAttempts)
            {
                attempts++;
                // 在中心附近取一个候选格
                IntVec3 root = CellFinder.RandomClosewalkCellNear(center, map, 50);
                if (!root.InBounds(map)) continue;

                Rot4 rot = Rot4.Random;

                IEnumerable<IntVec3> occupied = GenAdj.CellsOccupiedBy(root, rot, cursedGraveDef.Size);

                // 必须全部在地图内并且可站立
                if (occupied.Any(cell => !cell.InBounds(map) || !cell.Standable(map))) continue;

                // 避免与已有建筑重叠
                if (occupied.Any(cell => cell.GetFirstBuilding(map) != null)) continue;

                if (GenSpawn.WouldWipeAnythingWith(root, rot, cursedGraveDef, map, (Thing t) => true)) continue;

                // 通过检测，安全放置
                Thing newGrave = ThingMaker.MakeThing(cursedGraveDef);
                GenSpawn.Spawn(newGrave, root, map, rot, WipeMode.Vanish, false);
                placed++;
            }
            // 5. 散落一些纸钱 Filth
            ThingDef paperCoinFilth = ThingDef.Named("RI_Filth_PaperCoin");
            int filthCount = 80; // 生成80

            for (int i = 0; i < filthCount; i++)
            {
                IntVec3 c = CellFinder.RandomClosewalkCellNear(center, map, 50);
                if (!c.InBounds(map)) continue;

                FilthMaker.TryMakeFilth(c, map, paperCoinFilth, Rand.RangeInclusive(1, 3));
            }
        }
    }
}
